from flask import render_template, abort, request, send_from_directory, jsonify, flash, redirect, url_for
from flask_login import login_required, current_user

from app import app, db, modles
from app.utils.response_result import result, result_ok


@app.route('/sorts', methods=['GET'])
@login_required
def sorts():
    """查询分类列表
    :return:
    """
    w_sorts = modles.WebsiteSort.query.all();

    return render_template('website_sort/lists.html', sorts=w_sorts)


@app.route('/sorts/<int:sort_id>', methods=['GET'])
@login_required
def get_sort(sort_id):
    """根据 id 查询 一个分类

    :param sort_id:
    :return:
    """
    sort = modles.WebsiteSort.query.filter_by(id=sort_id).first()

    return render_template('website_sort/edit.html', sort=sort)


@app.route('/sorts', methods=['POST'])
@login_required
def post_sort():
    """创建一个分类
    :return:
    """
    name = request.form['name']

    if not name or len(name) > 25:
        flash('输入无效')
        return redirect(url_for('post_sort'))
    sort = modles.WebsiteSort(name=name)
    db.session.add(sort)
    db.session.commit()
    # return flask_ext.my_redirect('sorts', request)
    return redirect(url_for('sorts'))


@app.route('/sorts/<int:sort_id>', methods=['POST', 'PUT', 'DELETE'])
@login_required
def put_sort(sort_id):
    """根据 id 更新/删除 一个分类

    :param sort_id:
    :return:
    """
    _method = request.form['_method']
    sort = modles.WebsiteSort.query.filter_by(id=sort_id).first()

    # 更新
    if _method == 'PUT':
        name = request.form['name']
        if not name or len(name) > 25:
            flash('输入无效')
            return redirect(url_for('get_sort', sort_id=1))

        sort.name = name  # 更新名称
        db.session.commit()  # 提交数据库会话
        return redirect(url_for('sorts'))
    # 删除
    elif _method == 'DELETE':
        flash('删除成功')
        db.session.delete(sort)
        db.session.commit()
        return redirect(url_for('sorts'))
    else:
        flash('访问无效')
        return redirect(url_for('sorts'))


# @app.route('/sorts/<int:sort_id>', methods=['DELETE'])
# def delete_sort(sort_id):
"""根据 id 删除 一个分类
"""


@app.route('/api/sorts', methods=['GET'])
def get_sorts():
    """查询分类列表
    :return:
    """
    sorts = modles.WebsiteSort.query.filter_by(is_delete=0).all()

    return result_ok([item.website_sort_vo for item in sorts])